﻿from yazasport import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import REDIRECT_FIELD_NAME, authenticate, login
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from django.views.decorators.cache import never_cache
from userprofile.models import UserProfile
from userprofile.forms import UserCreationForm
from context_processor import user_context
from jinja2_shortcuts import render_to_response

def registration(request, template_name='registration/registration.html'):
    success, errors = [], []
    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.save()
            profile = UserProfile(first_name=new_user.first_name, last_name=new_user.last_name, user=new_user)
            profile.save()
            from settings import LOGIN_URL
            return HttpResponseRedirect(LOGIN_URL)
        else:
            errors.append(u'Исправьте ошибки в форме.')
    else:
        form = UserCreationForm()
    return render_to_response(template_name, {'form': form, 'errors': errors, 'success': success}, context_instance=user_context(request))
registration = never_cache(registration)
    
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
            	from settings import LOGIN_REDIRECT_URL
                redirect_to = LOGIN_REDIRECT_URL
            from django.contrib.auth import login
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)
    else:
        form = AuthenticationForm(request)
    request.session.set_test_cookie()
    return render_to_response(template_name, {'form': form, redirect_field_name: redirect_to,})
login = never_cache(login)

def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME):
    from django.contrib.auth import logout
    logout(request)
    if next_page is None:
        redirect_to = request.REQUEST.get(redirect_field_name, '')
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        else:
            return render_to_response(template_name, {})
    else:
        return HttpResponseRedirect(next_page or request.path)
